//
//  LeftPageViewController.m
//  MidProject
//
//  Created by student9 on 2020/12/1.
//  Copyright © 2020 itlab. All rights reserved.
//

#import "LeftPageViewController.h"

@interface LeftPageViewController () {
    NSString *name;
    NSString *email;
}

@end

@implementation LeftPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.personview = [[PersonViewController alloc] init];
    // 同步get操作
    NSString *urlString = @"http://172.18.178.56/api/user/info/self";
    NSURL *url = [NSURL URLWithString:urlString];
    // here, you will clear all cookies.
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSError *jsonError;
        NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
        if(jsonError) {
            // check the error description
            NSLog(@"json error : %@", [jsonError localizedDescription]);
        } else {
            // use the jsonDictionaryOrArray
            if ([jsonDictionaryOrArray[@"State"] isEqual: @"not_login"]) {
                [self gotoNotLoginPage];
            } else if ([jsonDictionaryOrArray[@"State"] isEqual: @"success"]) {
                self->email = (NSString*)jsonDictionaryOrArray[@"Email"];
                self->name = (NSString*)jsonDictionaryOrArray[@"Name"];
                [self gotoLoginPage];
            }
        }
        dispatch_semaphore_signal(semaphore);
    }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
}

- (void) gotoNotLoginPage {
    dispatch_async(dispatch_get_main_queue(), ^{
        __weak typeof(self) weakSelf = self;
        // Do any additional setup after loading the view.
        UIButton *login_btn;
        login_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        login_btn.frame = CGRectMake(0, 0, 150, 150);
        login_btn.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"notlogin.png"] TransformtoSize:CGSizeMake(150, 150)]];
        [login_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:login_btn.bounds cornerRadius:login_btn.frame.size.width/2];
        CAShapeLayer * maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = login_btn.bounds;
        maskLayer.path = maskPath.CGPath;
        login_btn.layer.mask = maskLayer;
        [login_btn addTarget:self
                      action:@selector(NotLoginButtonView:)
            forControlEvents:UIControlEventTouchUpInside];
        [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.view addSubview:login_btn];
        [login_btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).offset(weakSelf.view.frame.size.height / 6);
            // 添加大小约束（make就是要添加约束的控件view）
            make.size.mas_equalTo(CGSizeMake(150, 150));
            // 添加居中约束（居中方式与self相同）
            make.centerX.equalTo(weakSelf.view.mas_centerX);
        }];
        
        NSString *text=@"点击头像登录";
        TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, weakSelf.view.frame.size.width, 200)];
        label.font = [UIFont systemFontOfSize:14];
        label.numberOfLines = 0;
        [self.view addSubview:label];
        label.text=text;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).offset(weakSelf.view.frame.size.height / 3);
            make.right.equalTo(weakSelf.view).offset(55);
            // 添加大小约束（make就是要添加约束的控件view）
            make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width, 200));
            // 添加居中约束（居中方式与self相同）
        }];
        
    });
}

- (void) gotoLoginPage {
    dispatch_async(dispatch_get_main_queue(), ^{
        __weak typeof(self) weakSelf = self;
        // Do any additional setup after loading the view.
        UIButton *login_btn;
        login_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        login_btn.frame = CGRectMake(0, 0, 150, 150);
        login_btn.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"login.png"] TransformtoSize:CGSizeMake(150, 150)]];
        [login_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:login_btn.bounds cornerRadius:login_btn.frame.size.width/2];
        CAShapeLayer * maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = login_btn.bounds;
        maskLayer.path = maskPath.CGPath;
        login_btn.layer.mask = maskLayer;
        [login_btn addTarget:self
                      action:@selector(LoginButtonView:)
            forControlEvents:UIControlEventTouchUpInside];
        [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.view addSubview:login_btn];
        [login_btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).offset(weakSelf.view.frame.size.height / 6);
            // 添加大小约束（make就是要添加约束的控件view）
            make.size.mas_equalTo(CGSizeMake(150, 150));
            // 添加居中约束（居中方式与self相同）
            make.centerX.equalTo(weakSelf.view.mas_centerX);
        }];
        
        TTTAttributedLabel *namelabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, weakSelf.view.frame.size.width - 100, 50)];
        namelabel.font = [UIFont systemFontOfSize:35];
        namelabel.numberOfLines = 0;
        [self.view addSubview:namelabel];
        namelabel.text = self->name;
        [namelabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3);
            // 添加大小约束（make就是要添加约束的控件view）
            make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 50 * [namelabel.text length], 50));
            // 添加居中约束（居中方式与self相同）
            make.centerX.equalTo(weakSelf.view.mas_centerX);
        }];
        
        // 退出登录按钮
        UIButton *logout_btn;
        logout_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        logout_btn.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 50);
        logout_btn.backgroundColor = [UIColor colorWithRed:250/255.0 green:128/255.0 blue:114/255.0 alpha:1.0];
        [logout_btn setTitle:@"Logout" forState:UIControlStateNormal];
        [logout_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        UIBezierPath * maskPath_logout = [UIBezierPath bezierPathWithRoundedRect:logout_btn.bounds cornerRadius:10];
        CAShapeLayer * maskLayer_logout = [[CAShapeLayer alloc] init];
        maskLayer_logout.frame = logout_btn.bounds;
        maskLayer_logout.path = maskPath_logout.CGPath;
        logout_btn.layer.mask = maskLayer_logout;
        [logout_btn addTarget:self
                         action:@selector(logoutViewPush:)
               forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:logout_btn];
        [logout_btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3 + 200);
            // 添加大小约束（make就是要添加约束的控件view）
            make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
            // 添加居中约束（居中方式与self相同）
            make.centerX.equalTo(weakSelf.view.mas_centerX);
        }];
    });
}

-(void)setPersonview:(PersonViewController * )personview{
    if (self.personview == nil){
        self.personview = [[PersonViewController alloc] init];
    }
    self.personview = personview;
}

- (void)LoginButtonView:(UIButton *)buttonView {
    NSLog(@"已登录");
}

- (void)NotLoginButtonView:(UIButton *)buttonView {
    LoginViewController *testVC = [[LoginViewController alloc] init];
    //[testVC setPersonview:self.personview];
    UITabBarController* testVCnav = (UITabBarController*)self.delegate.centerViewController;
//    [testVCnav viewDidLoad];
    testVCnav.selectedIndex = 1;
    UINavigationController *nvc = testVCnav.viewControllers[1];
    [nvc pushViewController:testVC animated:NO];
    //当我们push成功之后，关闭我们的抽屉
    [self.delegate closeDrawerAnimated:YES completion:^(BOOL finished) {
        //设置打开抽屉模式为MMOpenDrawerGestureModeNone，也就是没有任何效果。
        [self.delegate setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    }];
//    [testVCnav viewDidLoad];
    
}

- (void)logoutViewPush: (UIButton *)buttonView {
    NSDictionary *usernameAndPassword = [[NSDictionary alloc] initWithObjectsAndKeys: self->email, @"name", nil ];
    NSString *urlString = @"http://172.18.178.56/api/user/logout";
    NSURL *url = [NSURL URLWithString:urlString];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:usernameAndPassword options:NSJSONWritingPrettyPrinted error:&error];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:jsonData];
    NSURLSession *session = [NSURLSession sharedSession];
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *return_data, NSURLResponse *response, NSError *error) {
        NSError *jsonError;
        NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:return_data options:kNilOptions error:&jsonError];
        if(jsonError) {
            // check the error description
            NSLog(@"json error : %@", [jsonError localizedDescription]);
        } else {
            // use the jsonDictionaryOrArray
            if ([jsonDictionaryOrArray[@"State"]  isEqual: @"success"]) {
                NSLog(@"json : success");
            } else {
                NSLog(@"json : error");
            }
        }
        dispatch_semaphore_signal(semaphore);
    }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    // 关闭我们的抽屉
    [self.delegate closeDrawerAnimated:YES completion:^(BOOL finished) {
        //设置打开抽屉模式为MMOpenDrawerGestureModeNone，也就是没有任何效果。
        [self.delegate setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    }];
    UITabBarController* testVCnav = (UITabBarController*)self.delegate.centerViewController;
//    [testVCnav viewDidLoad];
    testVCnav.selectedIndex = 1;
}

- (void) viewWillAppear:(BOOL)animated {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self viewDidLoad];
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
